package com.regis.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.regis.comment.CodeMsg;
import com.regis.comment.GlobalException;
import com.regis.comment.uilts.ThreadDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 计算机系 ITAEM 纱雾休比我老婆
 * @Description 登录过滤器
 * @date 2022/7/28 6:16
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Resource
    private RedisTemplate<Long,Long> redisTemplate;

    @ResponseBody
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        //直接放行的url
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        //判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //不需要则直接放行
        if(check){
            chain.doFilter(request,response);
            return;
        }

        //判断员工登录状态
        if(request.getSession().getAttribute("employee") != null ){
            Long id = (Long) request.getSession().getAttribute("employee");
            //将登录id保存到线程去
            ThreadDataUtil.setValue(id);
            chain.doFilter(request,response);
            return;
        }

        //判断用户登录状态
        if(request.getSession().getAttribute("user") != null){
            Long id = (Long) request.getSession().getAttribute("user");

            //将登录id保存到线程去
            ThreadDataUtil.setValue(id);
            chain.doFilter(request,response);
            return;
        }

        //若未登录
        throw new GlobalException(CodeMsg.STATE_ERROR);
    }

    /**
     * 判断本次请求是否可以放行
     * @param urls
     * @param requestURI
     * @return
     */
    public static boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean result = PATH_MATCHER.match(url, requestURI);
            if(result){
                return true;
            }
        }
        return false;
    }

}
